package com.goods.business.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.InStockInfoMapper;
import com.goods.business.mapper.InStockMapper;
import com.goods.business.mapper.ListMapper;
import com.goods.business.mapper.SupplierMapper;
import com.goods.business.service.InStockService;
import com.goods.common.model.business.InStock;
import com.goods.common.model.business.InStockInfo;
import com.goods.common.model.business.Product;
import com.goods.common.model.business.Supplier;
import com.goods.common.utils.JWTUtils;
import com.goods.common.vo.business.*;
import com.goods.common.vo.system.PageVO;
import com.google.gson.JsonObject;
import io.swagger.models.auth.In;
import org.apache.poi.hssf.record.DVALRecord;
import org.apache.shiro.authc.AuthenticationToken;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InStockServiceImpl implements InStockService {
    @Autowired
    private InStockMapper inStockMapper;
    @Autowired
    private InStockInfoMapper inStockInfoMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ListMapper listMapper;

    // 入库信息展示
    @Override
    public PageVO<InStockVO> findInStockList(FindInStockQueryVo findInStockQueryVo) {
        Integer pageNum = findInStockQueryVo.getPageNum();
        Integer pageSize = findInStockQueryVo.getPageSize();

        // 查询的开始时间和结束时间
        String startTime = findInStockQueryVo.getStartTime();
        String endTime = findInStockQueryVo.getEndTime();

        Date startDate = null;
        if(!StringUtils.isEmpty(startTime)){
            startDate = new Date(Long.valueOf(startTime));
        }
        Date endDate = null;
        if(!StringUtils.isEmpty(endTime)){
            endDate = new Date(Long.valueOf(endTime));
        }

        // 将页面传过来的放到对象中
        InStock inStock = new InStock();
        BeanUtils.copyProperties(findInStockQueryVo,inStock);

        // 从db中查询
        List<InStock> inStockList = inStockMapper.findInStockList(inStock,startTime,endTime);

        // 封装返回对象
        Date finalStartDate = startDate;
        Date finalEndDate = endDate;
        List<InStockVO> inStockVOList = inStockList.stream().map(i -> {
            InStockVO inStockVO = new InStockVO();
            // 获取操作人员的详细信息 根据id
            SupplierVO supplierVO = getSupplierVO(i.getSupplierId());
            BeanUtils.copyProperties(supplierVO,inStockVO); // 上面
            BeanUtils.copyProperties(i,inStockVO);// 因为后期查询明细的时候必须需要父订单的id 所以这个放在下面
            inStockVO.setStartTime(finalStartDate);
            inStockVO.setEndTime(finalEndDate);
            return inStockVO;
        }).collect(Collectors.toList());

        // 分页查询
        PageHelper.startPage(pageNum,pageSize);
        PageInfo inStockPageInfo = new PageInfo<>(inStockVOList);
        PageVO<InStockVO> inStockPageVO = new PageVO<>(inStockPageInfo.getTotal(),inStockVOList);

        return inStockPageVO;
    }

    // 查询入库信息明细
    @Override
    public InStockDetailVO detailInStock(Long id, Integer pageNum) {
        // 先根据id查询父订单
        InStock inStock = new InStock();
        inStock.setId(id);
        inStock = inStockMapper.selectOne(inStock);

        // 获取父订单的编号
        String inNum = inStock.getInNum();
        // 获取订单的状态
        Integer status = inStock.getStatus();
        // 获取操作人员
        String operator = inStock.getOperator();
        // 获取订单的类型
        Integer type = inStock.getType();
        // 获取联系人的id
        Long supplierId = inStock.getSupplierId();

        // 获取操作人员的详细信息 根据id
        SupplierVO supplierVO = getSupplierVO(supplierId);

        // 根据编号查询子订单
        InStockInfo inStockInfo = new InStockInfo();
        inStockInfo.setInNum(inNum);
        List<InStockInfo> inStockInfos = inStockInfoMapper.select(inStockInfo);

        // 子集
        List<InStockItemVO> itemVOS=inStockInfos.stream().map(i -> {
            InStockItemVO inStockItemVO = new InStockItemVO();
            // 获取商品编号
            String pNum = i.getPNum();
            // 根据商品编号查询商品详情
            Product product = new Product();
            product.setPNum(pNum);
            product = listMapper.selectOne(product);
            // 将商品详情的数据复制并返回
            BeanUtils.copyProperties(product,inStockItemVO);
            inStockItemVO.setCount(i.getProductNumber()); // 物资数量
            return inStockItemVO;
        }).collect(Collectors.toList());

        // 分页查询
        PageHelper.startPage(pageNum,3);
        PageInfo<InStockInfo> pageInfo = new PageInfo<>(inStockInfos);

        //返回数据封装
        InStockDetailVO inStockDetailVO = new InStockDetailVO();
        inStockDetailVO.setTotal(pageInfo.getTotal()); // 总记录数
        inStockDetailVO.setStatus(status); // 状态
        inStockDetailVO.setOperator(operator); // 操作人
        inStockDetailVO.setSupplierVO(supplierVO); // 操作人信息
        inStockDetailVO.setInNum(inNum); //订单编号
        inStockDetailVO.setType(type); // 订单类型
        inStockDetailVO.setItemVOS(itemVOS);

        // 返回数据
        return inStockDetailVO;
    }

    // 根据id获取联系人信息
    private SupplierVO getSupplierVO(Long supplierId) {
        Supplier supplier = new Supplier();
        supplier.setId(supplierId);
        supplier = supplierMapper.selectOne(supplier);
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier,supplierVO);
        return supplierVO;
    }

    // 修改状态
    @Override
    public void changeStatus(Long id, int status) {
        InStock inStock = new InStock();
        inStock.setId(id);
        inStock = inStockMapper.selectOne(inStock); // 先查询
        inStock.setStatus(status);
        inStockMapper.updateByPrimaryKey(inStock); // 在修改
    }

    // 删除入库信息
    @Override
    @Transactional
    public void deleteInStock(Long id) {
        // 根据id查询父订单
        InStock inStock = new InStock();
        inStock.setId(id);
        inStock = inStockMapper.selectOne(inStock);

        // 获取父订单的商品id
        String inNum = inStock.getInNum();

        // 删除子订单
        InStockInfo inStockInfo = new InStockInfo();
        inStockInfo.setInNum(inNum);
        inStockInfoMapper.delete(inStockInfo);

        // 删除父订单
        inStockMapper.delete(inStock);
    }

    // 新增入库
    @Override
    public void addIntoStock(InStockVO inStockVO, String username) {

        // 1、来源
        Long supplierId = inStockVO.getSupplierId();
        if(supplierId==null){ // 需要新增来源
            supplierId = insertSupplier(inStockVO);
        }

        // 2、生成随机订单号
        String inNum = UUID.randomUUID().toString().replaceAll("-", "");

        // 3.入库详情 [{productId:37,ProductNum:2},{productId:37,ProductNum:2},...]
        List<Object> products = inStockVO.getProducts();
        Integer countNum = 0;
        for (Object o : products) {
            Map map = JSONObject.parseObject(JSONObject.toJSONString(o),Map.class);
            Long productId = Long.valueOf(map.get("productId").toString()); // 商品id
            Integer productNum = Integer.valueOf(map.get("productNumber").toString()); // 商品数量
            countNum+=productNum; // 累加数量
            // 根据id查出商品详情
            Product product = new Product();
            product.setId(productId);
            product = listMapper.selectOne(product);
            // 入库详情表
            InStockInfo inStockInfo = new InStockInfo();
            inStockInfo.setInNum(inNum); // 入库号
            inStockInfo.setPNum(product.getPNum()); // 商品号
            inStockInfo.setProductNumber(productNum); // 商品数量
            inStockInfo.setCreateTime(new Date());
            inStockInfo.setModifiedTime(new Date());
            // 入库
            inStockInfoMapper.insert(inStockInfo);
        }

        // 4.入库
        InStock inStock = new InStock();
        inStock.setInNum(inNum); // 商品号
        inStock.setSupplierId(supplierId); // 来源联系人的id
        inStock.setStatus(2); // 状态 默认新增加的为待审核
        inStock.setOperator(username); // 操作者
        inStock.setRemark(inStockVO.getRemark()); // 备注
        inStock.setType(inStockVO.getType()); // 类型
        inStock.setCreateTime(new Date());
        inStock.setModified(new Date());
        inStock.setProductNumber(countNum); // 总数量
        inStockMapper.insert(inStock);
    }

    // 新增一条来源
    private long insertSupplier(InStockVO inStockVO) {
        Supplier supplier = new Supplier();
        supplier.setContact(inStockVO.getContact());
        supplier.setSort(inStockVO.getSort());
        supplier.setPhone(inStockVO.getPhone());
        supplier.setEmail(inStockVO.getEmail());
        supplier.setAddress(inStockVO.getAddress());
        supplier.setName(inStockVO.getName());
        supplier.setCreateTime(new Date());
        supplier.setModifiedTime(new Date());
        supplierMapper.insert(supplier);
        return supplier.getId();
    }
}
